﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using HtmlAgilityPack;
using TaobalLibrary.Requests;
using System.IO;
using Newtonsoft.Json.Linq;

namespace TaobaoLibrary
{
    public class Product
    {
        private string _html;
        private dynamic _config;
        private Dictionary<string, string> _microScopeData;

        public Product(HtmlNode node, Shop shop)
        {
            Name = node.SelectSingleNode("div[@class='desc']/a").InnerText.Trim();
            CoverUri = new Uri(node.SelectSingleNode("./div[@class='pic']/a/img").Attributes["data-ks-lazyload"].Value);
            Uri = new Uri(node.SelectSingleNode("div[@class='pic']/a").Attributes["href"].Value);
            Shop = shop;
        }

        private void LoadProductHtml()
        {
            if (_html == null)
            {
                _html = Requests.GetText(Uri.ToString());
                _config = ConfigParser.ParserConfigToObject(_html);
                _microScopeData = MicroScopeDataParser.ParseMicroScopeData(_html);
            }
        }

        public string Name { get; protected set; }

        public Image CoverImage
        {
            get
            {
                byte[] imageBytes = Requests.GetByte(CoverUri.ToString());
                MemoryStream stream = new MemoryStream(imageBytes);
                return Image.FromStream(stream);
            }
        }

        public Uri CoverUri { get; protected set; }

        public Uri Uri { get; protected set; }

        public Shop Shop { get; protected set; }

        public IList<Review> GetReviews()
        {
            LoadProductHtml();

            int maxPage = int.MaxValue;
            int currentPage = 1;
            List<Review> reviews = new List<Review>();

            while (currentPage < maxPage)
            {
                string url = "http://rate.taobao.com/feedRateList.htm?callback=jsonp_reviews_list&userNumId=" + _microScopeData["userid"] + "&auctionNumId=" + _config.itemId + "&siteID=" + _microScopeData["siteId"] + "&currentPageNum=" + (++currentPage) + "&rateType=&orderType=sort_weight&showContent=&attribute=";
                JToken jReviews = JsonpParser.ParseJsonpToObject(Requests.GetText(url));
                //comments是评论

                foreach (JToken comment in jReviews["comments"])
                {
                    reviews.Add(new Review(comment, this));
                }

                maxPage = (int)jReviews["maxPage"];
                currentPage = (int)jReviews["currentPageNum"];
            }

            return reviews;
        }
    }
}
